//
//  SizeImageView.m
//  PhotoLookManager
//
//  Created by ihope99 on 2017/8/4.
//  Copyright © 2017年 GZX. All rights reserved.
//

#import "SizeImageView.h"

@implementation SizeImageView{
    CGFloat currentScale;
}


-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
        self.maximumZoomScale = 4.0;
        self.minimumZoomScale = 1.0;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        
        mZoomView = [[UIImageView alloc]initWithFrame:CGRectMake(frame.origin.x,frame.origin.y,frame.size.width - 10, frame.size.height)];
        mZoomView.layer.masksToBounds = YES;
        mZoomView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:mZoomView];
        

    }
    return self;
}
-(void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    mZoomView.frame = CGRectMake(frame.origin.x,frame.origin.y,frame.size.width - 10, frame.size.height);
}

-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    currentScale = scale;
}

-(void)setImagePath:(NSString *)imagePath{
    _imagePath = imagePath;
    [mZoomView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        mZoomView.frame = [self getImageRect:image];
    }];
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return mZoomView;
}
- (CGRect)getImageRect:(UIImage *)image {
    int iWidth = self.frame.size.width;
    int iHeight = image.size.height*iWidth/image.size.width;
//    if (iHeight>self.frame.size.height) {
//        iHeight = self.frame.size.height;
//        iWidth = image.size.width*iHeight/image.size.height;
//    }
    if (iHeight < kScreenHeight) {
           return CGRectMake((self.frame.size.width-iWidth)/2, (self.frame.size.height-iHeight)/2, iWidth, iHeight);
    }
    else{
        
        self.contentSize = CGSizeMake(iWidth, iHeight);
         return CGRectMake((self.frame.size.width-iWidth)/2,0, iWidth, iHeight);
    }


}


//实现图片在缩放过程中居中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    float fWidth = scrollView.bounds.size.width;
    float fHeight = scrollView.bounds.size.height;
    float fContentWidth = scrollView.contentSize.width;
    float fContentHeight = scrollView.contentSize.height;
    CGFloat offsetX = (fWidth > fContentWidth)?(fWidth - fContentWidth)/2 : 0.0;
    CGFloat offsetY = (fHeight > fContentHeight)?(fHeight - fContentHeight)/2 : 0.0;
    mZoomView.center = CGPointMake(fContentWidth/2 + offsetX, fContentHeight/2 + offsetY);
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
